<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主体内容 -->
    <div class="flex min-h-screen">
      <!-- 右侧内容 -->
      <div class="w-full p-6">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-3 gap-6 mb-6">
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">待验收项目</div>
                <div class="text-2xl font-semibold">
                  {{ headerData.checkingProjectCount }}
                </div>
              </div>
              <el-icon class="text-purple-500 text-3xl"><Check /></el-icon>
            </div>
          </div>
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">已通过验收</div>
                <div class="text-2xl font-semibold">
                  {{ headerData.passedProjectCount }}
                </div>
              </div>
              <el-icon class="text-green-500 text-3xl"><CircleCheck /></el-icon>
            </div>
          </div>
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">验收通过率</div>
                <div class="text-2xl font-semibold">
                  {{ headerData.passRate }}%
                </div>
              </div>
              <el-icon class="text-blue-500 text-3xl"><DataLine /></el-icon>
            </div>
          </div>
        </div>

        <!-- 项目列表 -->
        <div class="bg-white rounded-lg shadow-sm">
          <el-table :data="executionsList" style="width: 100%">
            <el-table-column prop="fundProjects.id" label="项目编号" />
            <el-table-column prop="fundProjects.title" label="项目名称">
            </el-table-column>
            <el-table-column prop="fundProjects.applicantName" label="申请人" />
            <el-table-column prop="fundProjects.endDate" label="结题日期">
            </el-table-column>
            <el-table-column prop="fundProjects.level" label="验收评级">
            </el-table-column>
            <el-table-column prop="fundProjects.status" label="项目状态">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.fundProjects.status === '申请中'
                      ? 'info'
                      : row.fundProjects.status === '评审中'
                      ? 'primary'
                      : row.fundProjects.status === '执行中'
                      ? 'primary'
                      : row.fundProjects.status === '验收中'
                      ? 'info'
                      : row.fundProjects.status === '完成'
                      ? 'success'
                      : row.fundProjects.status === '驳回'
                      ? 'danger'
                      : 'info'
                  "
                >
                  {{ row.fundProjects.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="{ row }">
                <div class="flex space-x-2">
                  <el-button type="primary" link @click="handleDetail(row)"
                    >查看详情</el-button
                  >

                  <el-button
                    type="success"
                    link
                    @click="handlePass(row)"
                    :disabled="
                      row.fundProjects.status !== '验收中' ||
                      userStore.roles.includes('CEF_applicants')
                    "
                    >通过</el-button
                  >
                  <el-button
                    type="danger"
                    link
                    @click="handleClickReject(row)"
                    :disabled="
                      row.fundProjects.status !== '验收中' ||
                      userStore.roles.includes('CEF_applicants')
                    "
                    >驳回</el-button
                  >

                  <el-button
                    :disabled="row.fundProjects.status === '执行中'"
                    type="info"
                    link
                    @click="viewComments(row)"
                    >查看意见</el-button
                  >
                  <el-button type="primary" link @click="showReason(row)"
                  v-if="row.fundProjects.status === '延期结题'">延期原因
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex justify-end p-4">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :total="total"
              :page-sizes="[100]"
              layout="total, sizes, prev, pager, next"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </div>
        </div>
        <!-- 查看不通过对话框 -->
        <el-dialog v-model="showReasonDialog" title="延期原因" width="800px">
          <!-- <el-table :data="commentsList" style="width: 100%">
          <el-table-column  label="审核意见" />
        </el-table> -->

          <div class="text item">
            {{ reason }}
          </div>
        </el-dialog>
        <!-- 查看详情对话框 -->
        <el-dialog v-model="showFundsDialog" title="经费使用管理" width="800px">
          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <div class="text-lg font-medium">经费概览</div>
              <div class="flex space-x-4">
                <div class="text-gray-500">
                  总经费：<span class="text-black font-medium"
                    >{{ selectedProject.fundProjects.budget }} 万元</span
                  >
                </div>
                <div class="text-gray-500">
                  已用经费：<span class="text-black font-medium"
                    >{{ selectedProject.fundProjects.usedFund }} 万元</span
                  >
                </div>
                <div class="text-gray-500">
                  剩余经费：<span class="text-black font-medium"
                    >{{
                      selectedProject.fundProjects.budget -
                      selectedProject.fundProjects.usedFund
                    }}
                    万元</span
                  >
                </div>
              </div>
            </div>
            <el-progress
              :percentage="selectedProject.fundProjects.usedFundProgress"
            />
          </div>

          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <div class="text-lg font-medium">经费使用记录</div>
            </div>
            <el-table :data="fundProjectExpenses" style="width: 100%">
              <el-table-column
                prop="expenseDate"
                label="使用日期"
                width="120"
              />
              <el-table-column prop="expenseType" label="用途类型" width="120">
              </el-table-column>
              <el-table-column prop="description" label="用途说明" />
              <el-table-column
                prop="expenseAmount"
                label="金额(万元)"
                width="120"
              />
            </el-table>
            <br />
            <p class="text-lg font-medium">相关文件</p>
            <el-form-item>
              <!-- 上传文件 -->
              <file-upload
                :fileSize="10"
                :limit="2"
                :disabled="true"
                v-model="progressForm.midTermReport"
                :handleFileClick="handleClickFile"
              ></file-upload>
            </el-form-item>
          </div>
        </el-dialog>

        <!-- 驳回对话框 -->
        <el-dialog v-model="showRejectDialog" title="驳回项目" width="500px">
          <el-form :model="rejectForm" label-width="80px">
            <el-form-item label="驳回意见" prop="reviewComments">
              <el-input
                v-model="rejectForm.reviewComments"
                type="textarea"
                placeholder="请输入驳回意见"
                :rows="4"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showRejectDialog = false">取 消</el-button>
              <el-button type="primary" @click="handleReject()"
                >确 定</el-button
              >
            </div>
          </template>
        </el-dialog>

        <!-- 查看意见对话框 -->
        <el-dialog
          v-model="showCommentsDialog"
          title="项目意见列表"
          width="800px"
        >
          <!-- <el-table :data="commentsList" style="width: 100%">
            <el-table-column  label="审核意见" />
          </el-table> -->

          <div v-for="item in commentsList" :key="item" class="text item">
            {{ item }}
          </div>
        </el-dialog>

        <!-- 通过评价对话框 -->
        <el-dialog v-model="showPassDialog" title="项目验收评价" width="500px">
          <el-form :model="passForm" label-width="80px">
            <el-form-item label="评价等级" prop="level">
              <el-select v-model="passForm.level" placeholder="请选择评价等级">
                <el-option label="优秀" value="优秀" />
                <el-option label="良好" value="良好" />
                <el-option label="通过" value="通过" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="showPassDialog = false">取 消</el-button>
              <el-button type="primary" @click="submitPass()">确 定</el-button>
            </div>
          </template>
        </el-dialog>

        <el-dialog
          title="研究计划文档"
          v-model="docDialogVisible"
          width="80%"
          append-to-body
          destroy-on-close
        >
          <div class="w-full overflow-auto">
            <vue-office-docx
              v-if="previewType === 'docx' || previewType === 'doc'"
              :src="src"
            />
            <vue-office-pdf v-if="previewType === 'pdf'" :src="src" />
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup name="Executions">
import {
  listExecutions,
  getExecutions,
  delExecutions,
  addExecutions,
  updateExecutions,
  pass,
  reject,
  rejectOpinion,
  rejectList,
  getReason,
} from "@/api/project/check"

import {
  addExpenses,
  delExpenses,
  getExpenses,
  listExpenses,
  updateExpenses,
} from "@/api/project/expense.js"

import VueOfficeDocx from "@vue-office/docx"
import VueOfficePdf from "@vue-office/pdf"
import { getCheckData } from "@/api/project/view.js"
import useUserStore from "@/store/modules/user"
import { nextTick } from "vue"
const userStore = useUserStore()
console.log(userStore.roles)
getCheckData().then((res) => {
  headerData.value = res.data
})

const { proxy } = getCurrentInstance()

const headerData = ref({})
const executionsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const showProgressDialog = ref(false)

const showFundsDialog = ref(false)
const showAddFundRecord = ref(false)
const selectedProject = ref({})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    projectId: null,
    midTermReport: null,
    midTermDate: null,
    executionStatus: null,
    progress: null,
    remarks: null,
  },
  newFundRecord: {
    projectId: null,
    expenseAmount: null,
    expenseDate: null,
    expenseType: null,
    description: null,
  },
  rules: {
    projectId: [{ required: true, message: "项目ID不能为空", trigger: "blur" }],
    executionStatus: [
      { required: true, message: "执行状态不能为空", trigger: "change" },
    ],
    progress: [
      { required: true, message: "项目进度不能为空", trigger: "blur" },
    ],
    updateTime: [
      { required: true, message: "状态更新时间不能为空", trigger: "blur" },
    ],
  },
})

const { queryParams, form, rules, newFundRecord } = toRefs(data)

const reason = ref("")
const showReasonDialog = ref(false)
const showReason = (row) => {
  debugger
  showReasonDialog.value = true
  // 根据后端返回的数据，TODO
  reason.value = row.delayReason
}

/** 查询项目执行记录列表 */
function getList() {
  loading.value = true
  listExecutions(queryParams.value).then((response) => {
    executionsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    midTermReport: null,
    midTermDate: null,
    executionStatus: null,
    progress: null,
    remarks: null,
    updateTime: null,
  }
  proxy.resetForm("executionsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["executionsRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateExecutions(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addExecutions(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
const fundProjectExpenses = ref([])
const handleDetail = (row) => {
  selectedProject.value = row
  fundProjectExpenses.value = row.fundProjectExpenses
  progressForm.value = row
  progressForm.value.id = row.id
  showFundsDialog.value = true
  newFundRecord.value.projectId = row.projectId
}

const progressForm = ref({
  id: null,
  progress: 0,
  midTermReport: null,
})

const updateProgress = (row) => {
  progressForm.value = row
  progressForm.value.id = row.id
  console.log(progressForm)
  showProgressDialog.value = true
}
const submitProgress = () => {
  console.log("提交进度更新", progressForm.value)
  updateExecutions(progressForm.value).then((response) => {
    proxy.$modal.msgSuccess("修改成功")
    showProgressDialog.value = false
    getList()
  })
}

/** 查询项目费用记录列表 */
function getFundList() {
  loading.value = true
  getExecutions(newFundRecord.value.projectId).then((response) => {
    fundProjectExpenses.value = response.data.fundProjectExpensesList
    selectedProject.fundProjects.usedFund = response.data.usedFund
    selectedProject.fundProjects.usedFundProgress =
      response.data.usedFundProgress
    total.value = response.total
    loading.value = false
  })
}

/** 提交按钮 */
function submitFundRecord() {
  addExpenses(newFundRecord.value).then((response) => {
    proxy.$modal.msgSuccess("新增成功")
    showAddFundRecord.value = false
    getFundList()
  })
}

// 通过对话框相关变量
const showPassDialog = ref(false)
const passForm = ref({
  projectId: null,
  level: "通过",
})

// 点击通过按钮，打开通过对话框
const handlePass = (row) => {
  passForm.value.projectId = row.fundProjects.id
  passForm.value.level = "通过"
  showPassDialog.value = true
}

// 提交通过评价
const submitPass = () => {
  pass({
    id: passForm.value.projectId,
    level: passForm.value.level,
  }).then((response) => {
    proxy.$modal.msgSuccess("审核通过")
    showPassDialog.value = false
    getList()
  })
}

// 驳回对话框相关变量
const showRejectDialog = ref(false)
const rejectForm = ref({
  projectId: null,
  reviewComments: "",
})

// 点击驳回按钮，打开驳回对话框
const handleClickReject = (row) => {
  rejectForm.value.projectId = row.fundProjects.id
  rejectForm.value.reviewComments = ""
  showRejectDialog.value = true
}

// 提交驳回
const handleReject = (row) => {
  if (!rejectForm.value.reviewComments) {
    proxy.$modal.msgError("请输入驳回意见")
    return
  }
  rejectOpinion(rejectForm.value).then((response) => {
    proxy.$modal.msgSuccess("驳回成功")
    showRejectDialog.value = false
    getList()
  })
}

// 查看驳回意见对话框
const showCommentsDialog = ref(false)
const commentsList = ref([])

// 查看驳回意见
const viewComments = (row) => {
  console.log(row.fundProjects.id)
  rejectList({ projectId: row.fundProjects.id }).then((response) => {
    if (response.data != null) {
      commentsList.value = response.data.commonList
      if (!response.data.commonList) {
        proxy.$modal.msgError("暂无驳回意见")
        return
      }
      showCommentsDialog.value = true
    }
  })
}

// 下载文件
const downloadFile = (filePath) => {
  if (filePath) {
    // 使用系统提供的下载工具
    proxy.$download.resource(filePath)
  } else {
    proxy.$modal.msgError("文件不存在")
  }
}

const previewType = ref("")
const src = ref("")
const docDialogVisible = ref(false)
const getFileExtension = (filename) => {
  return filename
    .slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2)
    .toLowerCase()
}
function handleView(url) {
  if (url) {
    fetch(url)
      .then((response) => {
        if (!response.ok) throw new Error("Network response was not ok")
        previewType.value = getFileExtension(url)
        return response.arrayBuffer()
      })
      .then((arrayBuffer) => {
        src.value = arrayBuffer // 将文件内容赋值给src，vue-office-docx组件会自动渲染
        docDialogVisible.value = true // 显示文档对话框
      })
      .catch((error) => {
        console.error("Failed to fetch the document:", error)
      })
  }
}

const handleClickFile = (url) => {
  console.log(url)
  handleView(url)
}
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  console.log("页码切换为:", val)
  // 确保在状态更新后再获取数据
  nextTick(() => {
    getList()
  })
}

function handleSizeChange(val) {
  queryParams.value.pageSize = val
  queryParams.value.pageNum = 1
  console.log("每页条数切换为:", val)
  // 确保在状态更新后再获取数据
  nextTick(() => {
    getList()
  })
}

// 确保初始化时获取数据列表
getList()
</script>
<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.el-menu {
  border-right: none;
}
:deep(.el-upload-dragger) {
  width: 100%;
}
:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 11px;
}
:deep(.el-dialog__body) {
  padding: 20px 40px;
}
:deep(.el-progress-bar__outer) {
  background-color: #f0f2f5;
}
:deep(.el-slider__runway) {
  margin: 15px 0;
}
:deep(.el-table__expanded-cell) {
  padding: 0 !important;
}
</style>
